<template>
  <div class="home">
    <h1>欢迎使用语音技术吧</h1>
    <p>你的登录状态为：{{loginStatusText}}</p>
    <p v-if="user">你的Authing用户标识为：{{user.id}}</p>
    <p v-if="userProfile">你的账户ID为：{{userProfile.id}}</p>
    <p v-if="userProfile">你的昵称为：{{userProfile.nickname}}</p>
    <button v-if="user" @click="$router.push({path:'/me'})">点我前往个人页</button>
    <button v-if="!user" @click="$router.push({path:'/login'})">点我去登陆</button>
    <button v-else @click="logOut">点我登出</button>
    <button @click="clearCache">清除缓存</button>
    <article-summary-card :articleInfo="fakeArticleInfo"/>
  </div>
</template>

<script>
// @ is an alias to /src
import {getAuthClientWithToken,checkLoginStatus,retrieveAuthingUser} from '@/utils/authing'
import {getSelfProfile} from '@/utils/api/me'
import {storeUserProfile,retrieveUserProfile,removeUserProfile} from '@/utils/storage'
import ArticleSummaryCard from '@/components/ArticleSummaryCard'

const fakeArticleInfo = {
  author_id: 1,
  article_id: 1,
}

export default {
  name: 'HomeView',
  components: {
    ArticleSummaryCard
},
  computed: {
    user () {
      return this.$store.state.user
    },
    loginStatusText() {
      return this.user === null ? "未登录":"已登录"
    },
    userProfile () {
      return this.$store.state.userProfile
    },
    fakeArticleInfo() {
      return fakeArticleInfo
    }
  },
  methods: {
    async logOut() { //清除VUEX中记录的全局状态以及localStorage存储的信息
      await getAuthClientWithToken(this.user.token).logout()
      removeUserProfile()
      this.$store.commit('setUser',null)
      this.$store.commit('setUserProfile',null)
      this.$toast.success("已登出")
      localStorage.clear()
      this.$router.replace({path:'/login'})
    },
    async loadNetworkProfile() {
      //判断登录状态
      const loggedIn = await checkLoginStatus()
      if (!loggedIn) {this.$store.commit('setUserProfile',null);return;}
      const profileResult = await getSelfProfile()
      //更新localStorage中的profile值
      storeUserProfile(profileResult.data)
      this.$store.commit('setUserProfile',profileResult.data)
    },
    loadLocalProfile() {
      const profile = retrieveUserProfile()
      if (profile) {
      //更新vuex
      this.$store.commit('setUserProfile',profile)
      }
    },
    clearCache() {
      this.$store.commit('setUser',null)
      this.$store.commit('setUserProfile',null)
      localStorage.clear()
    }
  },
  mounted() {
    this.loadLocalProfile()
    retrieveAuthingUser().then(
    (user)=>{this.$store.commit('setUser',user);this.loadNetworkProfile();})
  },
}
</script>
